package com.epam.tcs;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.epam.tcs.actions.Action;
import com.epam.tcs.actions.ActionFactory;
import com.epam.tcs.filters.User;

public class ViewServlet extends HttpServlet{

	private static final long serialVersionUID = -8101237040387640105L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doAction(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doAction(req, resp);
	}

	private void doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		req.setCharacterEncoding("utf-8");
		
		HttpSession session = req.getSession();
		
		if (session.getAttribute("user") != null) {
		
			User user = (User) session.getAttribute("user"); 
			
			try {
				Action actionclass = ActionFactory.getAction(user.getRole());				
				if (actionclass != null) {
					actionclass.doExec(req, resp);
				} else {
					resp.sendRedirect("/tcs");
				}				
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
		
	}
	
	public void outputPage(String aJSPName, HttpServletRequest aRequest,
			HttpServletResponse aResponse) throws IOException, ServletException {
		
		RequestDispatcher dispatcher = aRequest.getRequestDispatcher("/jsp/"
				+ aJSPName);
		dispatcher.forward(aRequest, aResponse);
	}
	
	
}
